package com.jrzh.intercepter.sys;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.jrzh.common.cache.Cache;
import com.jrzh.common.cache.CacheManager;
import com.jrzh.common.utils.IpUtil;
import com.jrzh.framework.I18nHelper;
import com.jrzh.framework.annotation.NoAdminLogin;
import com.jrzh.framework.annotation.NoPermission;
import com.jrzh.framework.annotation.RequiredPermission;
import com.jrzh.framework.annotation.UserEvent;
import com.jrzh.framework.bean.ResultBean;
import com.jrzh.framework.bean.SessionUser;
import com.jrzh.mvc.constants.CacheConstants;
import com.jrzh.mvc.constants.SysActionConstants;
import com.jrzh.mvc.model.sys.UserEventModel;
import com.jrzh.mvc.service.sys.UserEventServiceI;

public class SysInterceptor implements HandlerInterceptor {
	Log log = LogFactory.getLog(SysInterceptor.class);
	@Resource(name="userEventService")
	private UserEventServiceI userEventService;
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserEvent userEvent = null;
		NoAdminLogin noAdminLogin = null;
		NoPermission noPermission = null;
		RequiredPermission requiredPermission = null;
		Method method = null;
		if(handler instanceof HandlerMethod){
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			method = handlerMethod.getMethod();
			userEvent = method.getAnnotation(UserEvent.class);
			noAdminLogin = method.getAnnotation(NoAdminLogin.class);
			noPermission = method.getAnnotation(NoPermission.class);
			requiredPermission = method.getAnnotation(RequiredPermission.class);
		}
		if(null != noAdminLogin) return true;
		
		String requestUrl = request.getRequestURI();
		Boolean isAdmin = requestUrl.indexOf("/admin/") > 0;
		Boolean isLoginUrl = requestUrl.indexOf("/login.json") > 0;
		String uuid = request.getParameter("uuid");
		SessionUser sessionUser = null;
		if(StringUtils.isNotBlank(uuid)){
			Cache cache = CacheManager.getCacheInfo(uuid);
			if(null != cache){
				sessionUser = (SessionUser) cache.getValue();
			}
		}
		if(isAdmin) {
			if(null == sessionUser && !isLoginUrl){
				ResultBean result = new ResultBean();
				result.setMsg(I18nHelper.getI18nByKey("message.no_login", sessionUser));
				result.setStatus("no_login");
			    response.setCharacterEncoding("UTF-8"); 
				response.getWriter().print(JSONObject.toJSONString(result));
				return false;
			}else{
				//刷新登陆缓存
				CacheManager.clearOnly(uuid);
				CacheManager.putCacheInfo(uuid, sessionUser, CacheConstants.LOGIN_TIME_OUT);
			}
			
			if(null == noPermission && null == requiredPermission) {
				ResultBean result = new ResultBean();
				result.setMsg(I18nHelper.getI18nByKey("message.no_register_permission", sessionUser));
				result.setStatus("no_register_permission");
			    response.setCharacterEncoding("UTF-8"); 
				response.getWriter().print(JSONObject.toJSONString(result));
				return false;
			}
			
			if(null != requiredPermission) {
				String key = requiredPermission.key();
				String[] request_array = requestUrl.split("/admin/");
				String module = request_array[0].replace("/", "");
		        String[] func_array = request_array[1].split("/");
	        	String func_two = func_array[0];
	        	String func_three = "";
	        	String requiredCode_two = module+"/html_" + func_two +"_index";
	        	String requiredCode_three = "";
	        	if(func_array.length > 1){
	        		func_three = func_array[0] + "_" + func_array[1];
	        		requiredCode_three = module+"/html_" + func_three +"_index";
	        	}
				if(!SysActionConstants.INDEX.equals(key)) {
					requiredCode_two = requiredCode_two + "_" + key;
					requiredCode_three = requiredCode_three + "_" + key;
				}

				Boolean hasPermission = false;
				//权限判断
				Set<String> resources = (Set<String>)sessionUser.getAttrs().get("resources");
				for(String resourceCode : resources) {
					if(StringUtils.equals(requiredCode_two, resourceCode) || 
					   StringUtils.equals(requiredCode_three, resourceCode)) {
						hasPermission = true;break;
					}
				}
				
				if(!hasPermission) {
					ResultBean result = new ResultBean();
					result.setMsg(I18nHelper.getI18nByKey("message.no_permission", sessionUser));
					result.setStatus("no_permission");
				    response.setCharacterEncoding("UTF-8"); 
					response.getWriter().print(JSONObject.toJSONString(result));
					return false;
				}
			}
			
			if(null != userEvent && null != sessionUser && null != method){
				String desc = StringUtils.isBlank(userEvent.desc()) ? "访问了" + method.getName() : userEvent.desc();
				addUserEvent(request, desc, method.toString(), sessionUser);
			}
		}
		return true;
	}
	
	private void addUserEvent(HttpServletRequest request, String desc, String handler ,SessionUser user) throws Exception{
		UserEventModel userEvent = new UserEventModel();
		userEvent.setUserId(user.getId());
		userEvent.setIp(IpUtil.getIpAddr(request));
		userEvent.setTime(new Date());
		userEvent.setDescription(desc);
		userEvent.setHandlerName(handler);
		userEventService.add(userEvent, user);
	}
}
